package com.ajmd.onlineexam.service;

import com.ajmd.onlineexam.entity.ImagePO;
import com.ajmd.onlineexam.entity.OptionPO;
import com.ajmd.onlineexam.mapper.ImageMapper;
import com.ajmd.onlineexam.mapper.OptionMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ajmd
 * @since 2023/5/6 17:18
 */
@Service
public class OptionService {
    @Resource
    private OptionMapper optionMapper;
    @Resource
    private ImageMapper imageMapper;

    /**
     * 根据试题id删除选项和图片（题库试题、试卷试题、考试试题
     * @param questionIds
     */
    public void deleteOptionAndImg(List<String> questionIds){
        List<String> imageBelongIds = new ArrayList<>();
        imageBelongIds.addAll(questionIds);
        //使用questionIds查出所有optionId
        LambdaQueryWrapper<OptionPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(OptionPO::getBelongQuestionId, questionIds);
        List<OptionPO> optionPOList = optionMapper.selectList(queryWrapper);
        if(ObjectUtils.isNotEmpty(optionPOList)){
            List<String> optionIds = optionPOList.stream().map(OptionPO::getId).collect(Collectors.toList());
            imageBelongIds.addAll(optionIds);
            //删除选项
            optionMapper.deleteBatchIds(optionIds);
        }
        //删除图片
        LambdaQueryWrapper<ImagePO> imagePOLambdaQueryWrapper = new LambdaQueryWrapper<>();
        imagePOLambdaQueryWrapper.in(ImagePO::getBelongId,imageBelongIds);
        imageMapper.delete(imagePOLambdaQueryWrapper);
    }
}
